export default class {
  constructor(lrc) {
    this.lrc = lrc;
    this.lyric = this._parseLyric(lrc?.lrc?.lyric || '');
    this.tlyric = this._parseLyric(lrc?.tlyric?.lyric || '');
    this.lyricuser = lrc.lyricUser;
    this.transuser = lrc.transUser;
  }

  // 给一个时间，返回 歌词 的 索引
  seek(startTime = 0) {
    return this._findCurNum(startTime) - 1;
  }

  // 查找索引
  _findCurNum(time) {
    for (let i = 0; i < this.lyric.length; i++) {
      if (time <= this.lyric[i].time) {
        return i;
      }
    }
    return this.lyric.length;
  }

  // 解析歌词
  _parseLyric(lrc) {
    const lyrics = lrc.split('\n');
    let lrcObj = [];
    for (let i = 0; i < lyrics.length; i++) {
      const lyric = decodeURIComponent(lyrics[i]);
      const timeReg = /\[\d*:\d*((\.|:)\d*)*\]/g;
      const timeRegExpArr = lyric.match(timeReg);
      if (!timeRegExpArr) continue;
      const content = lyric.replace(timeReg, '');
      for (let k = 0, h = timeRegExpArr.length; k < h; k++) {
        const t = timeRegExpArr[k];
        const min = Number(String(t.match(/\[\d*/i)).slice(1));
        const sec = Number(String(t.match(/:\d*/i)).slice(1));
        const ms = Number(t.match(/\d*\]/i)[0].slice(0, 2)) / 100;
        const time = min * 60 + sec + ms;
        if (content !== '') {
          lrcObj.push({ time: time, rawTime: timeRegExpArr[0], content });
        }
      }
    }
    lrcObj.sort((a, b) => a.time - b.time);
    return lrcObj;
  }
}
